package com.twu.biblioteca;


import java.util.ArrayList;

public class BibliotecaGuiBooksTab {

    private ArrayList<Book> booksList;
    private ConsoleHandler console;

    public BibliotecaGuiBooksTab(){
        console = new ConsoleHandler();
        FileHandler fileHandler = new FileHandler();
        BooksListParser booksParser = new BooksListParser();
        booksList = booksParser.parseXml(fileHandler.loadFile("src/com/twu/biblioteca/LibraryBooks"));
    }

    public void displayBooksTab(){
        console.printLineMsg("List of Available Books:");
        printBooksList();
        printReservationMsgAndHandlesAnswer();
    }

    private void printBooksList(){
        for(int index = 0; index < booksList.size(); index++){
            int outputIndex = index + 1;
            console.printMsg(outputIndex + "- ");
            console.printLineMsg(booksList.get(index).getBookInfo().getName());
        }
    }

    private void printReservationMsgAndHandlesAnswer(){

        console.printLineMsg("\nDo you want to reserve a book? Yes(y) or No(n)");
        String userSelection = console.readLineMsg();

        if(isReservationAnswerValid(userSelection))
            verifiesAndPerformReservationIfUserDesires(userSelection);
        else {
            console.printLineMsg("Please select a valid option!");
            printReservationMsgAndHandlesAnswer();
        }
    }

    private boolean isReservationAnswerValid(String userSelection){
        if(!userSelection.equals("n") && !userSelection.equals("N") &&
                !userSelection.equals("Y") && !userSelection.equals("y"))
            return false;

        return true;
    }

    private void verifiesAndPerformReservationIfUserDesires(String userDesire){
        if(userDesire.equals("y") || userDesire.equals("Y")) {
            console.printLineMsg("Please select the book number to be reserved:");
            int bookIndex = validateBookIndex(console.readLineMsg());

            if( bookIndex == -1){
                console.printLineMsg("Please select a valid option!");
                verifiesAndPerformReservationIfUserDesires(userDesire);
            }

            console.printLineMsg(booksList.get(bookIndex-1).ReserveBook());
            printReservationMsgAndHandlesAnswer();
        }
    }

    private int validateBookIndex(String consoleInput){
        try {
            int bookIndex = Integer.parseInt(consoleInput);
            if(bookIndex >0 && bookIndex <= booksList.size())
                return bookIndex;
            else
                return -1;
        } catch (NumberFormatException e) {
            return -1;
        }
    }

}
